package cn.com.yang.thread;

import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;

/**
 * 自定义实现重入锁
 * @author 杨亿金
 * @date 2022年9月1日-下午8:37:50
 * @since 1.0.0
 */
public class TestReetrantLock1 implements Lock{
	// 锁标志
	private boolean isLocked = false;
	// 定义同一个线程获取锁的次数
	int lockCount = 0;
	// 定义一个线程
	Thread thread =null;
	
	

	@Override
	public synchronized void lock() {
		Thread cuThread = Thread.currentThread();
		while(isLocked && cuThread!=thread) {
			try {
				wait();
			} catch (InterruptedException e) {
				e.printStackTrace();
			}
		}
		//第一次进来，将锁标志设置为true
		isLocked = true;
		thread =cuThread;
		//计数器自增
		lockCount ++;
	}
	
	@Override
	public void lockInterruptibly() throws InterruptedException {
		// TODO Auto-generated method stub
		
	}

	@Override
	public Condition newCondition() {
		// TODO Auto-generated method stub
		return null;
	}

	@Override
	public boolean tryLock() {
		// TODO Auto-generated method stub
		return false;
	}

	@Override
	public boolean tryLock(long var1, TimeUnit var3) throws InterruptedException {
		// TODO Auto-generated method stub
		return false;
	}

	@Override
	public synchronized void unlock() {
		if (thread == Thread.currentThread()) {
			lockCount --;
			if (lockCount ==0) {
				notify();
				isLocked =false;
			}
		}
	}
}
